package ch.bfh.mobicomp.ui.in;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import ch.bfh.mobicomp.AlarmManager;
import ch.bfh.mobicomp.R;

public class AlarmActivity extends Activity
		implements OnCheckedChangeListener, OnClickListener{
	private static final String tag="AlarmActivity";
	private SharedPreferences pref;
	private CheckBox checkBoxLight;
	private CheckBox checkBoxAcceleration;
	private CheckBox checkBoxCompass;
	private Button button;
	public static final String SP_NAME = "ch.bfh.mobicomp.Alarm";
	public static final String SP_KEY_ALARM_LIGHT = "alarmLight";
	public static final String SP_KEY_ALARM_ACCELERATION = "alarmAcceleration";
	public static final String SP_KEY_ALARM_COMPASS = "alarmCompass";
	public static final String SP_KEY_SERVICE_STATE = "serviceState";
	Toast toast;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        this.pref = getSharedPreferences(SP_NAME, MODE_PRIVATE);
        
        this.checkBoxLight = (CheckBox) findViewById(R.id.checkBox_light);
		this.checkBoxAcceleration = (CheckBox) findViewById(R.id.checkBox_accelerator);
		this.checkBoxCompass = (CheckBox) findViewById(R.id.checkBox_compass);
		this.button = (Button) findViewById(R.id.button_start);
		
		Log.d(tag, "SP_KEY_ALARM_LIGHT" + pref.getBoolean(SP_KEY_ALARM_LIGHT, false));
		Log.d(tag, "SP_KEY_ALARM_ACCELERATION" + pref.getBoolean(SP_KEY_ALARM_ACCELERATION, false));
		Log.d(tag, "SP_KEY_ALARM_COMPASS" + pref.getBoolean(SP_KEY_ALARM_COMPASS, false));
		Log.d(tag, "SHARED_PREFERENCES_KEY_START_BUTTON: " +  pref.getBoolean(SP_KEY_SERVICE_STATE, false));
		if(!pref.getBoolean(SP_KEY_SERVICE_STATE, false)) {
			setViewEnabled();
		} else {
			setViewDisabled(false);
		}
		this.checkBoxCompass.setOnCheckedChangeListener(this);
		this.checkBoxAcceleration.setOnCheckedChangeListener(this);
		this.checkBoxLight.setOnCheckedChangeListener(this);
		this.button.setOnClickListener(this);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.main_menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if(item.getItemId() == R.id.menu_settings){
    		startActivity(new Intent(this, SettingsActivity.class));
    		return true;
    	}
    	return false;
    }

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		Log.d(tag, "Shared pref pressed");
		Editor editor = pref.edit();
		editor.putBoolean(SP_KEY_ALARM_LIGHT, checkBoxLight.isChecked());
		editor.putBoolean(SP_KEY_ALARM_ACCELERATION, checkBoxAcceleration.isChecked());
		editor.putBoolean(SP_KEY_ALARM_COMPASS, checkBoxCompass.isChecked());
		editor.commit();
		Log.d(tag, "SP_KEY_ALARM_LIGHT" + pref.getBoolean(SP_KEY_ALARM_LIGHT, false));
		Log.d(tag, "SP_KEY_ALARM_ACCELERATION" + pref.getBoolean(SP_KEY_ALARM_ACCELERATION, false));
		Log.d(tag, "SP_KEY_ALARM_COMPASS" + pref.getBoolean(SP_KEY_ALARM_COMPASS, false));
	}

	@Override
	public void onClick(View v) {
		Log.d(tag, "Startbutton clicked. Button Text: " + button.getText());
		Editor editor = pref.edit();
		if(!pref.getBoolean(SP_KEY_SERVICE_STATE, false))
		{
			setViewDisabled(true);
			CountDownTimer countdown = new CountDown(6000, 1000);
			toast = Toast.makeText(getBaseContext(), "6", Toast.LENGTH_SHORT);
			toast.show();
			countdown.start();
			editor.putBoolean(SP_KEY_SERVICE_STATE, true);
		} else {
			editor.putBoolean(SP_KEY_SERVICE_STATE, false);
			Intent broadcastIntent = new Intent(AlarmManager.INTENT_ALARM_CONFIG_CHANGED);
			this.sendBroadcast(broadcastIntent);
		}
		editor.commit();
		Log.d(tag, "Sending Intent: AlarmManager.INTENT_ALARM_CONFIG_CHANGED");
	}

	private void setViewDisabled(boolean progress){
		Log.d(tag, "setViewDisabled()");
		if(progress){
			button.setText(getString(R.string.act_main_button_progress));
			button.setEnabled(false);
		} else {
			button.setText(getString(R.string.act_main_button_stop));
			button.setEnabled(true);
		}
		updateCheckBoxes();
		checkBoxAcceleration.setEnabled(false);
		checkBoxCompass.setEnabled(false);
		checkBoxLight.setEnabled(false);
		
	}
	
	private void setViewEnabled(){
		Log.d(tag, "setViewEnabled()");
		button.setText(getString(R.string.act_main_button_start));
		updateCheckBoxes();
		checkBoxAcceleration.setEnabled(true);
		checkBoxCompass.setEnabled(true);
		checkBoxLight.setEnabled(true);
	}
	
	private void updateCheckBoxes(){
		this.checkBoxLight.setChecked(pref.getBoolean(SP_KEY_ALARM_LIGHT, false));
		this.checkBoxAcceleration.setChecked(pref.getBoolean(SP_KEY_ALARM_ACCELERATION, false));
		this.checkBoxCompass.setChecked(pref.getBoolean(SP_KEY_ALARM_COMPASS, false));
	}
	
	//BroadcastReceiver to update the Activity, when the Service changes
    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
        	Log.d(tag, "Got Broadcast");
    		String action = intent.getAction();
    		if (action.equals(AlarmManager.INTENT_ALARM_CONFIG_CHANGED)) {
    			if(pref.getBoolean(SP_KEY_SERVICE_STATE, false)){
    				Log.d("AlarmActivity", "AlarmActivity received INTENT_SERVICE_ON: disable view");
    				setViewDisabled(false);
    			} else {
    				Log.d("AlarmActivity", "AlarmActivity received INTENT_SERVICE_ON: enable view");
    				setViewEnabled();
    			}
    		} else {
    			throw new RuntimeException("Unknown intent");
    		}
        }
    };
    
        @Override
        protected void onResume() {
            IntentFilter filter = new IntentFilter();
            filter.addAction(AlarmManager.INTENT_ALARM_CONFIG_CHANGED);
            registerReceiver(receiver, filter);
            super.onResume();
        }

        @Override
        protected void onPause() {
            unregisterReceiver(receiver);
            super.onPause();
        }
        
	public class CountDown extends CountDownTimer{
		public CountDown(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			toast.cancel();
			toast.setText("Service starts in "+Integer.toString((int)(millisUntilFinished / 1000))+" sec.");
			toast.show();
		}
		
		@Override
		public void onFinish() {
			toast.cancel();
			Intent broadcastIntent = new Intent(AlarmManager.INTENT_ALARM_CONFIG_CHANGED);
			sendBroadcast(broadcastIntent);
			setViewDisabled(false);
		}
	} 
}